package com.thinksns.sociax.t4.android.weiba;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.Api;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.component.SmallDialog;
import com.thinksns.sociax.t4.exception.UpdateException;
import com.thinksns.sociax.t4.exception.VerifyErrorException;
import com.thinksns.sociax.t4.model.ModelBackMessage;
import com.thinksns.sociax.t4.model.ModelComment;
import com.thinksns.sociax.thinksnsbase.activity.widget.ListFaceView;
import com.thinksns.sociax.thinksnsbase.exception.ApiException;
import com.thinksns.sociax.thinksnsbase.utils.UnitSociax;
import com.thinksns.sociax.thinksnsbase.utils.WordCount;


/**
 * Created by Catherine on 2016/9/30.
 * 输入评论
 * 需要传入参数：
 * type  eg：评论帖子COMMENT_POST
 * id ：帖子id
 * comment 回复某条评论
 */

public class ActivityCommentInput extends ThinksnsAbscractActivity implements View.OnClickListener {
    private static final int MSG_COMMENT_POST = 0X1; // 评论帖子
    public static final String COMMENT_POST = "post_comment"; // 代表评论帖子的

    private EditText et_send_content;
    private ImageView img_face;
    private TextView overWordCount;
    private LinearLayout btn_layout;

    private boolean isFace = false;//默认显示键盘
    private ListFaceView face_view;
    private String type;//评论的类型
    private int id;//资源id
    private ModelComment comment;
    private String hint;//用于提示回复了谁
    private int to_comment_id;
    private int to_uid;
    private SmallDialog smallDialog;//发送评论提示框
    private WordCount mWordCount;   //文字字数限制

    private Handler mCommentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_COMMENT_POST:
                    smallDialog.dismiss();
                    ModelBackMessage backMessage = (ModelBackMessage) msg.obj;
                    ToastUtils.showToast(backMessage.getMsg());
                    if (backMessage != null && 1 == backMessage.getStatus()) {
                        setResult(RESULT_OK);
                        finish();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        initIntent();
        super.onCreate(savedInstanceState);
        initViews();
        initListener();
        initData();
    }

    @Override
    public String getTitleCenter() {
        return "";
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_comment_input;
    }

    public void initIntent() {
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        id = intent.getIntExtra("id", 0);
        comment = (ModelComment) intent.getSerializableExtra("comment");
        if (comment != null) {
            if (!TextUtils.isEmpty(comment.getRemark())){
                hint = String.format(getString(R.string.comment_format_reply), comment.getRemark());
            }else{
                hint = String.format(getString(R.string.comment_format_reply), comment.getUname());
            }
            to_comment_id = comment.getComment_id();
            to_uid = Integer.parseInt(comment.getUid());
        }
    }

    //设置输入字数长度限制
    private void setInputLimit() {
        mWordCount = new WordCount(et_send_content, overWordCount);
        overWordCount.setText(String.valueOf(mWordCount.getMaxCount()));
        et_send_content.addTextChangedListener(mWordCount);
    }

    public void initViews() {
        btn_layout = (LinearLayout) findViewById(R.id.btn_layout);
        et_send_content = (EditText) findViewById(R.id.et_send_content);
        img_face = (ImageView) findViewById(R.id.img_face);
        overWordCount = (TextView) findViewById(R.id.overWordCount);
        face_view = (ListFaceView) findViewById(R.id.face_view);
        face_view.initSmileView(et_send_content);
        if (!TextUtils.isEmpty(hint)) {
            et_send_content.setHint(hint);
        }
        smallDialog = new SmallDialog(this, "发送中..");
    }

    public void initData() {
        setInputLimit();
        //默认显示键盘
        setFace(isFace);
    }

    public void initListener() {
        onKeyBoard();
        img_face.setOnClickListener(this);
        et_send_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                face_view.setVisibility(View.GONE);
                isFace = false;
                setFace(isFace);
                return false;
            }
        });
    }

    @Override
    protected CustomTitle setCustomTitle() {
        return new LeftAndRightTitle(this, "取消", "发布");
    }

    @Override
    public View.OnClickListener getRightListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = et_send_content.getText().toString();
                if (TextUtils.isEmpty(content.trim())) {
                    ToastUtils.showToast(getResources().getString(R.string.alert_no_content));
                    return;
                }
                if (content.length() > 140) {
                    ToastUtils.showToast(getResources().getString(R.string.out_of_content_length));
                    return;
                }
                // 组装评论内容
                ModelComment myComment = new ModelComment();
                myComment.setComment_id(id);
                if (comment != null) {
                    content = "回复@" + comment.getUname() + "：" + content;
                    myComment.setReplyCommentId(comment.getComment_id());
                }
                myComment.setContent(content);
                smallDialog.show();
                // 根据不同传入的 type 去提交评论
                if (COMMENT_POST.equals(type)) {
                    //评论帖子
                    doCommentPost(myComment);
                }
            }
        };
    }

    /**
     * 执行评论帖子
     * @param comment
     */
    private void doCommentPost(final ModelComment comment) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ModelBackMessage backMessage = new Api.WeibaApi().replyPost(comment);
                    Message msg = mCommentHandler.obtainMessage();
                    msg.obj = backMessage;
                    msg.what = MSG_COMMENT_POST;
                    mCommentHandler.sendMessage(msg);
                } catch (ApiException e) {
                    e.printStackTrace();
                } catch (VerifyErrorException e) {
                    e.printStackTrace();
                } catch (UpdateException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public View.OnClickListener getLeftListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UnitSociax.hideSoftKeyboard(ActivityCommentInput.this, et_send_content);
                finish();
            }
        };
    }

    private void setFace(boolean isFace) {
        if (isFace) {
            img_face.setImageResource(R.drawable.key_bar);
            UnitSociax.hideSoftKeyboard(this, et_send_content);
        } else {
            img_face.setImageResource(R.drawable.face_bar);
            UnitSociax.showSoftKeyborad(this, et_send_content);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_face:
                if (face_view.getVisibility() == View.GONE) {
                    setFace(true);
                    face_view.setVisibility(View.VISIBLE);
                    isFace = true;
                } else if (face_view.getVisibility() == View.VISIBLE) {
                    face_view.setVisibility(View.GONE);
                    setFace(false);
                    isFace = false;
                }

                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        UnitSociax.hideSoftKeyboard(this, et_send_content);
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        UnitSociax.showSoftKeyborad(this, et_send_content);
    }

    private void onKeyBoard() {
        LinearLayout layout = (LinearLayout) findViewById(R.id.ll_main_content);
        layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //判断窗口可见区域大小  
                Rect r = new Rect();
                // getWindowVisibleDisplayFrame()会返回窗口的可见区域高度  
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
                int mScreenHeight = UnitSociax.getWindowHeight(ActivityCommentInput.this);
                int heightDifference = mScreenHeight - (r.bottom - r.top);
                boolean isKeyboardShowing = heightDifference > mScreenHeight / 3;
                if (isKeyboardShowing) {
                    btn_layout.animate().translationY(-heightDifference + UnitSociax.getDecorViewHeight(ActivityCommentInput.this)).setDuration(0).start();
                } else {
                    btn_layout.animate().translationY(0).start();
                }
            }
        });
    }
}
